#include "utils.h"
#include <QWindow>

#if _MSC_VER
#include <Windows.h>
#endif

HWND _WORKERW = nullptr;

BOOL CALLBACK EnumWindowsProc(_In_ HWND tophandle, _In_ LPARAM topparamhandle)
{
    HWND defview = FindWindowEx(tophandle, 0, L"SHELLDLL_DefView", nullptr);
    if (defview != nullptr)
    {
        _WORKERW = FindWindowEx(0, tophandle, L"WorkerW", 0);
    }

    return TRUE;
}

WId viewId;
LRESULT CALLBACK HookShoot(_In_ int nCode, _In_ WPARAM wParam,LPARAM lParam)
{
    if(wParam == WM_MOUSEMOVE || wParam == WM_NCMOUSEMOVE)
    {
         MOUSEHOOKSTRUCT * mshook = (MOUSEHOOKSTRUCT *)lParam;
         PostMessageA((HWND)viewId,WM_MOUSEMOVE,0,MAKELPARAM(mshook->pt.x,mshook->pt.y));
    };

    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

HWND GetWorkerW()
{
    int result;
    HWND windowHandle = FindWindow(L"Progman", nullptr);
    //使用 0x3e8 命令分割出两个 WorkerW
    SendMessageTimeout(windowHandle, 0x052c, 0 ,0, SMTO_NORMAL, 0x3e8,(PDWORD_PTR)&result);
    //遍历窗体获得窗口句柄
    EnumWindows(EnumWindowsProc,(LPARAM)nullptr);
    // 显示WorkerW
    ShowWindow(_WORKERW,SW_HIDE);
    return windowHandle;
}

void Utils::updateWallpaper(QQmlApplicationEngine& engine)
{
    QObject *qmlObj = engine.rootObjects().first();
    QWindow *qmlWindow=qobject_cast<QWindow *>(qmlObj);
    viewId = qmlWindow->winId();

    HWND workerW =  GetWorkerW();
    GetWindowLongA((HWND)viewId, GWL_STYLE);
    SetParent((HWND)viewId,workerW);
    SetWindowPos((HWND)viewId,HWND_TOP,0,0,0,0,WS_EX_LEFT|WS_EX_LTRREADING|WS_EX_RIGHTSCROLLBAR|WS_EX_NOACTIVATE);
    HHOOK hook = SetWindowsHookExA(WH_MOUSE_LL,HookShoot,GetModuleHandle(NULL),0);
    qmlWindow->showMaximized();
}
